# Please install OpenAI SDK first: `pip3 install openai`
import sys
import io

from openai import OpenAI

# 设置标准输入输出的编码为 UTF-8
sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

def on_response(user_context):
    client = OpenAI(api_key="sk-7b780b0898154b4aa091acb173d4da2e", base_url="https://api.deepseek.com")

    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "system", "content": "You are a helpful assistant"},
            {"role": "user", "content": user_context},
        ],
        stream=True
    )
    return response

def stream_out(response):
    # print(response.choices[0].message.content)
    for chunk in response:
        if hasattr(chunk, 'choices') and len(chunk.choices) > 0:
            delta = chunk.choices[0].delta
            if hasattr(delta, 'content') and delta.content:  # 检查是否有 content 属性
                print(delta.content, end='')
    print("\n")
def main():
    while 1:
        user_context = input("User: ")
        if user_context == "exit":
            break
        response = on_response(user_context)
        stream_out(response)

if __name__ == '__main__':
    main()